const fs = require('fs')
const path = require('path')
const semver = require('semver') // 版本比较
const colors = require('colors') // 颜色

const package = JSON.parse(fs.readFileSync(
  path.join(__dirname, 'package.json')
))

//const request = require('request') // 网络请求
// 测试用
function request (url, callback) {
  callback(
    null,
    { statusCode: 200 },
    JSON.stringify({ version: '0.2.0' })
  )
}

function getLatest () {
  const url = `https://registry.npmjs.org/${package.name}/latest`
  return new Promise((resolve, reject) => {
    request(url, (err, response, body) => {
      if (err || response.statusCode !== 200) {
        console.log(response, response.statusCode === 200)
        reject('[error] could not get lastest version\n' + err)
      } else {
        resolve(JSON.parse(body).version)
      }
    })
  })
}

function notifyLatest (latest) {
  if (semver.gt(latest, package.version)) {
    console.log(`[info] ${package.name}`
    + ` ${package.version} => ${latest} `.brightYellow
    + 'is available!')
  }
}

module.exports = {
  checkNode (condition) {
    if (!semver.satisfies(process.version, condition)) {
      console.error(`[error] require version ${condition}, current = ${process.version}`)
      process.exit(1)
    }
  },
  checkLatest () {
    getLatest().then(notifyLatest).catch(console.error)
  }
}
